
/****************************************************************************
  From Qt examples
****************************************************************************/

#include "sslserverthread.h"

#include <QtNetwork>
#include <iostream>
using namespace std;

SSLThread::SSLThread(int socketDescriptor, const QString &message, QObject *parent)
    : QThread(parent), socketDescriptor(socketDescriptor), text(message)
{
    this->socketDescriptor = socketDescriptor;
}

void SSLThread::run()
{
    //Thread starts here
    blockS=0;
    qDebug()<< socketDescriptor << "Starting Thread";
    //socket = new QTcpSocket(); OLD

    serverSocket = new QSslSocket;

    // We need to read in the local certificate and
    // and the private key that we generated
    // with openssl.  Read the README to see
    // how these are generated.
    serverSocket->setLocalCertificate("cacert.pem");
    serverSocket->setPrivateKey("privkey.pem");


    // check that the certificate / private key are not null
    if (serverSocket->localCertificate().isNull()) {
       qDebug() << "WARNING: The local certificate appears to be null! ";
    }
    if (serverSocket->privateKey().isNull()) {
       qDebug() << "WARNING: The private key appears to be null! ";
    }

    // debug message on success
    qDebug() << "Created the SSL socket, Read local cert. / private key files";

    // From incoming connection we obtain the socket descriptor,
    // we associate this with our new SSL socket

    //Thread is used for sending and recieving data from the clients
     if (serverSocket->setSocketDescriptor(socketDescriptor))
     {
         connect(serverSocket, SIGNAL(readyRead()), this, SLOT(readyRead()),Qt::DirectConnection);
         serverSocket->startServerEncryption();
     }
         else
         {
             emit error(serverSocket->error());
             qDebug() << "Socket Problem";
             return;

         }

    connect(serverSocket,SIGNAL(disconnected()),this,SLOT(disconnect()),Qt::DirectConnection);

    qDebug()<< socketDescriptor << "Client Connected";

    //start the event loop of the thread
    exec();

}

void SSLThread::readyRead()
{


    qDebug() << "Original blockSize: " << blockS;

    //QDataStream in(socket);
    QDataStream in(serverSocket);
    in.setVersion(QDataStream::Qt_4_0);

    if (blockS == 0) {
        if (serverSocket->bytesAvailable() < (int)sizeof(quint16))
            return;
        in >> blockS;
    }

    qDebug() << "BlockSize: " << blockS;

    if (serverSocket->bytesAvailable() < blockS)
    {
        qDebug() << "available bytes problem: " << blockS;
        return;
    }

    qDebug() << "Recieved the full msg";

    //
    QString msg;
    in >> msg;
    text = msg;


    qDebug() << socketDescriptor << "Message in: " << msg;

    emit clientMessage(msg);//to display the client msg on the screen


    //socket->write(Data);
    //qDebug() << "Server Write back";
}


void SSLThread::sendData(QString msg)
{

        qDebug() << "Writing to:" << socketDescriptor;


        QByteArray block;
        QDataStream out(&block, QIODevice::WriteOnly);
        out.setVersion(QDataStream::Qt_4_0);
        out << (quint16)0;
        out << msg;
        out.device()->seek(0);
        out << (quint16)(block.size() - sizeof(quint16));

        //qDebug() << "Thread got request, but waiting 2 seconds to respond..." << endl;
        //sleep(2);

        qDebug() << "Server writing: " << msg << endl;
        qDebug() << "Server writing: " << block << endl;
        serverSocket->write(block);
        qDebug() << "Thread sent Message request to: " << socketDescriptor << endl;
        //tcpSocket.waitForBytesWritten();

       serverSocket->disconnectFromHost();//TESTING

        //serverSocket->waitForDisconnected(3000);//wait for 3 secs max
        //socketDescs.removeLast();




}


void SSLThread::disconnect()
{
    qDebug() << socketDescriptor << "Disconnecting: ";
    serverSocket->deleteLater();
    exit(0); // Thread no longer needed
}


